package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.*;
import com.gable.exhibition.dao.*;
import com.gable.exhibition.model.*;
import com.gable.exhibition.service.UserService;
import com.gable.exhibition.util.*;
import com.gable.exhibition.view.UserView;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Lesson on 2017/12/28.
 */

@Controller
@RequestMapping(value="/user")
public class UserController extends ActionSupport{

        Logger logger = Logger.getLogger(UserController.class);
        private String code;

        public String getCode() {
                return code;
        }


        public void setCode(String code) {
                this.code = code;
        }

        @Autowired
        UserService userService;

        @Autowired
        UserDao userDao;

        @Autowired
        HospitalDao hospitalDao;

        @Autowired
        ManufacturerDao manufacturerDao;

        @Autowired
        SupplierDao supplierDao;

        @Autowired
        CommissionDao commissionDao;

        //获取凭证校检接口
        @RequestMapping(value="/getOpenId",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil getOpenId(String code){
            try {
                ReturnResultUtil rru = userService.getOpenId(code);
                return rru;
            }catch (Exception e){
                e.printStackTrace();
            }
            return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        }


        @RequestMapping(value="/userLoginByWeb",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil userLoginByWeb(HttpServletRequest request , HttpServletResponse response, UserView user){
                try {
                        ReturnResultUtil rru = checkLoginUser(user,1);
                        if(rru != null){
                                return rru;
                        }
                        rru =  userService.userLoginByWeb(user);
                        User user1 = CacheData.getSessionUser(null,1);
                        if(user1 == null || (user1.getType().longValue() == 1102 || user1.getType().longValue() == 1103|| user1.getType().longValue() == 1105|| user1.getType().longValue() == 1106)){
                                return new ReturnResultUtil(500,MessageUtil.NONPLATFORMUSERSCANNOTLOGIN);
                        }
                        return rru;

                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.LOGINEXCEPTION);
        }

        @RequestMapping(value="/userLoginByApp",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil userLoginByApp(HttpServletRequest request , HttpServletResponse response, UserView userView){
                try {
                        if(userView.getLoginType() == null){
                                return new ReturnResultUtil(500,MessageUtil.CHOICELOGINTYPE);
                        }
                        if(userView.getLoginType()==3){
                                if(userView.getOpenId() == null){
                                        return new ReturnResultUtil(500,"OpenId不能为空");
                                }
                        }

                        int loginType = userView.getLoginType();

                        if(loginType <1 || loginType > 3){
                                return new ReturnResultUtil(500,MessageUtil.LOGINTYPEERROR);
                        }

                        ReturnResultUtil rru = checkLoginUser(userView,loginType);
                        if(rru != null){
                                return rru;
                        }
                        rru = userService.userLoginByApp(userView);
                        if(rru.getRet()  == 500){
                                return rru;
                        }
                        if(rru.getData() == null){
                                return rru;
                        }
                        UserView loginUser = (UserView) rru.getData();
                        if(loginUser.getType().longValue() == 1104){
                                return new ReturnResultUtil(500,MessageUtil.NOHOSPITALSERVICELOGIN);
                        }
                        logger.info(JSON.toJSONString(rru));
                        userService.updateUserLastLoginTime(loginUser.getUserId(),true);
                        return rru;
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.LOGINEXCEPTION);
        }


        /**
         * 校验用户登录参数
         * @param userView
         * @Create user jacky
         * @Create date 2018/2/5
         * @return
         */
        public ReturnResultUtil checkLoginUser (UserView userView,int loginType){
                if(loginType!=3){
                        if (StringUtil.isEmpty(userView.getUserName())) {
                                return new ReturnResultUtil(500, MessageUtil.USERNAMECANNOTEMPTY);
                        }
                        if(loginType == 1){
                                if (StringUtil.isEmpty(userView.getPassword())) {
                                        return new ReturnResultUtil(500, MessageUtil.PASSWORDCANNOTEMPTY);
                                }
                        }
                }
                return  null;
        }


        @RequestMapping(value="/page")
        public String page(HttpServletRequest request , HttpServletResponse response){
                return "user/user-page";
        }

        @RequestMapping(value = "/logout", produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil logout(HttpServletRequest request,HttpServletResponse response){
                Long userId = null;
                if(!StringUtil.isEmpty(request.getParameter("userId"))){
                        userId = Long.parseLong(request.getParameter("userId"));
                }
                if(userId != null){
                        CheckImportExcelHospital.resultMap.remove(userId);
                        CheckImportExcelManufacturer.resultMap.remove(userId);
                        CheckImportExcelMaintainer.resultMap.remove(userId);
                        CheckImportExcelDevice.resultMap.remove(userId);
                        CheckImportExcelContract.resultMap.remove(userId);
                        CheckImportExcelContract.resultMap1.remove(userId);
                        CheckImportExcelEstimate.resultMap.remove(userId);
                        CheckImportExcelEstimate.resultMap1.remove(userId);
                }

                CacheData.deleteSessionUser(userId);
                return new ReturnResultUtil(200,MessageUtil.LOGINOUTSUCCESS);
        }

        @RequestMapping(value = "/updatePassword",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil updatePassword(HttpServletRequest request,HttpServletResponse response){
                try {

                        if (StringUtil.isEmpty(request.getParameter("newPassword"))) {
                                return new ReturnResultUtil(500, MessageUtil.NEWPASSWORDDCANNOTEMPTY);
                        }

                        if (StringUtil.isEmpty(request.getParameter("confirmPassword"))) {
                                return new ReturnResultUtil(500, MessageUtil.CONFIRMPASSWORDDCANNOTEMPTY);
                        }

                        String oldPassword = request.getParameter("oldPassword");
                        String newPassword = request.getParameter("newPassword");
                        String confirmPassword = request.getParameter("confirmPassword");

                        if (!newPassword.equals(confirmPassword)) {
                                return new ReturnResultUtil(500, MessageUtil.NEWCONFIRMEPASSWORDSNOTCONSISTENT);
                        }

                        Long userId = null;
                        int type = 2;
                        if (!StringUtil.isEmpty(request.getParameter("userId"))) {
                                userId = Long.parseLong(request.getParameter("userId"));
                                type = 1;
                        }
                        UserView user = CacheData.getSessionUser(userId, type);
                        UserView userView = new UserView();
                        userView.setUserId(user.getUserId());
                        userView.setOldPassword(oldPassword);
                        userView.setNewPassword(newPassword);
                        return userService.updatePassword(userView);
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.UPDATEPASSWORDEXCEPTION);
        }

        @RequestMapping(value = "/queryUserTermInit",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryUserTermInit(HttpServletRequest request,HttpServletResponse response){
                try{
                        String type = request.getParameter("type");
                        Map map = new HashMap();
                        map.put("type",type);
                        ReturnResultUtil rru = userService.queryUserTermInit(map);
                        logger.info(JSON.toJSONString(rru));
                        return  rru;
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.UPDATEPASSWORDEXCEPTION);
        }

        @RequestMapping(value = "/queryUserList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryUserList(HttpServletRequest request,HttpServletResponse response,UserView userView){
                try{
                        ReturnResultUtil rru = userService.queryUserList(userView);
                        logger.info(JSON.toJSONString(rru));
                        return rru;
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        }

        @RequestMapping(value = "/addOrUpdateUser",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil addOrUpdateUser(HttpServletRequest request,HttpServletResponse response,UserView userView){
                try{
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Long userId = null;
                        if(!StringUtil.isEmpty(request.getParameter("userId"))){
                                userId = Long.parseLong(request.getParameter("userId"));
                        }
                        UserView userView1 = CacheData.getSessionUser(userId,1);
                        if(userView.getUserId() == null){
                                userView.setCreatePerson(userView1.getUserId());
                                userView.setCreateTime(df.format(new Date()));
                        }else{
                                userView.setUpdatePerson(userView.getUserId());
                                userView.setUpdateTime(df.format(new Date()));
                        }
                        return userService.addOrUpdateUser(userView);
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

        @RequestMapping(value = "/queryUserInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryUserInfo(HttpServletRequest request,HttpServletResponse response,UserView userView){
                try{
                        if(StringUtil.isEmpty(request.getParameter("userId"))){
                                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
                        }

                        Long userId = Long.parseLong(request.getParameter("userId"));
                        return userService.queryUserInfo(userId);
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

        @RequestMapping(value = "/queryUser",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil queryUser(HttpServletRequest request,UserView userView){
                ReturnResultUtil resultUtil = new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
                try {
                        Long maintainerId = userView.getMaintainerId();
                        if(maintainerId == null)
                                return new ReturnResultUtil(500,MessageUtil.MAINTAINERIDISNULL);
                        resultUtil = userService.queryUser(userView);
                } catch (Exception e) {
                        e.printStackTrace();
                }
                return resultUtil;
        }


        @RequestMapping(value = "/loginErrorByPost",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil loginErrorByPost(HttpServletRequest request){
                String type = (String)request.getAttribute("type");
                if(type.equals("1")){
                        return new ReturnResultUtil(600,MessageUtil.SESSIONNOTEXITIS);
                }else  if( type.equals("2")){
                        return new ReturnResultUtil(601,MessageUtil.AUTHORITYERROR);
                }
                return new ReturnResultUtil(200);
        }

        @RequestMapping(value = "/loginErrorByGet")
        public String loginErrorByGet(HttpServletRequest request){

                return "redirect:/";
        }

        @RequestMapping(value = "/completionUserInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil completionUserInfo(HttpServletRequest request,UserView userView){
                        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try{
                        if(StringUtil.isEmpty(userView.getMobile())){
                                return new ReturnResultUtil(500,MessageUtil.MOBILECANNOTEMPTY);
                        }
                        if(StringUtil.isEmpty(userView.getPassword())){
                                return new ReturnResultUtil(500,MessageUtil.PASSWORDCANNOTEMPTY);
                        }
                        if(userView.getType() == null){
                                return new ReturnResultUtil(500,MessageUtil.USERTYPEISNULL);
                        }
                        if(StringUtil.isEmpty(userView.getUserName())){
                                return new ReturnResultUtil(500,MessageUtil.USERNAMECANNOTEMPTY);
                        }

                        ReturnResultUtil rru = checkUser(userView);
                        if(rru != null)
                        return rru;

                        return userService.completionUserInfo(userView);
                }catch (Exception e){
                        e.printStackTrace();
                }

                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }



        public ReturnResultUtil checkUser(UserView user){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             if(user.getInsertType() != null) {
                     if (user.getInsertType() == 0) {
                             if (user.getType() == 1101) {
                                     if (user.getHospitalId() == null) {
                                             return new ReturnResultUtil(500, MessageUtil.HOSPITALID);
                                     } else {
                                             user.setTag(1002L);
                                     }
                             } else if (user.getType() == 1102) {
                                     if (user.getManufacturerId() == null) {
                                             return new ReturnResultUtil(500, MessageUtil.MANUFACTURERIDISNULL);
                                     } else {
                                             user.setTag(1004L);
                                     }
                             } else if (user.getType() == 1105) {
                                     if (user.getSupplierId() == null) {
                                             return new ReturnResultUtil(500, MessageUtil.SUPPLIERIDISNULL);
                                     } else {
                                             user.setTag(1009L);
                                     }
                             } else if (user.getType() == 1106) {
                                     if (user.getCommissionId() == null) {
                                             return new ReturnResultUtil(500, MessageUtil.COMMISSIONIDISNULL);
                                     } else {
                                             user.setTag(1011L);
                                     }
                             }
                     } else if (user.getInsertType() == 1) {
                             if (user.getType() == 1101) {
                                     if (StringUtil.isEmpty(user.getAllName())) {
                                             return new ReturnResultUtil(500, MessageUtil.HOSPITALNAMEISNULL);
                                     } else {
                                             Hospital hospital = new Hospital();
                                             hospital.setHospitalId(UUIDGenerator.getUniqueLong());
                                             hospital.setProvinceId(user.getProvinceId());
                                             hospital.setCityId(user.getCityId());
                                             hospital.setAreaId(user.getAreaId());
                                             hospital.setHospitalName(user.getAllName());
                                             hospital.setCreateTime(sdf.format(new Date()));
                                             hospital.setIsDel(0);
                                             int result = hospitalDao.insertSelective(hospital);
                                             if (result > 0) {
                                                     user.setHospitalId(hospital.getHospitalId());
                                                     user.setTag(1002L);
                                             }
                                     }
                             } else if (user.getType() == 1102) {
                                     if (StringUtil.isEmpty(user.getAllName())) {
                                             return new ReturnResultUtil(500, MessageUtil.MANUFACTURERNAMEISNULL);
                                     } else {
                                             Manufacturer manufacturer = new Manufacturer();
                                             manufacturer.setManufacturerId(UUIDGenerator.getUniqueLong());
                                             manufacturer.setProvinceId(user.getProvinceId());
                                             manufacturer.setCityId(user.getCityId());
                                             manufacturer.setAreaId(user.getAreaId());
                                             manufacturer.setManufacturerName(user.getAllName());
                                             manufacturer.setCreateTime(sdf.format(new Date()));
                                             manufacturer.setIsDel(0);
                                             int result = manufacturerDao.insertSelective(manufacturer);
                                             if (result > 0) {
                                                     user.setManufacturerId(manufacturer.getManufacturerId());
                                                     user.setTag(1004L);
                                             }

                                     }
                             } else if (user.getType() == 1105) {
                                     if (StringUtil.isEmpty(user.getAllName())) {
                                             return new ReturnResultUtil(500, MessageUtil.SUPPLIERNAMEISNULL);
                                     } else {
                                             Supplier supplier = new Supplier();
                                             supplier.setSupplierId(UUIDGenerator.getUniqueLong());
                                             supplier.setProvinceId(user.getProvinceId());
                                             supplier.setCityId(user.getCityId());
                                             supplier.setAreaId(user.getAreaId());
                                             supplier.setSupplierName(user.getAllName());
                                             supplier.setCreateTime(sdf.format(new Date()));
                                             supplier.setIsDel(0);
                                             int result = supplierDao.insertSelective(supplier);
                                             if (result > 0) {
                                                     user.setSupplierId(supplier.getSupplierId());
                                                     user.setTag(1009L);
                                             }
                                     }
                             } else if (user.getType() == 1106) {
                                     if (StringUtil.isEmpty(user.getAllName())) {
                                             return new ReturnResultUtil(500, MessageUtil.COMMISSIONNAMEISNULL);
                                     } else {
                                             Long commissionId = commissionDao.checkCommission(user.getAllName());
                                             if(commissionId != null){
                                                     user.setCommissionId(commissionId);
                                                     user.setTag(1010L);
                                             }else{
                                                     Commission commission = new Commission();
                                                     commission.setCommissionId(UUIDGenerator.getUniqueLong());
                                                     commission.setProvinceId(user.getProvinceId());
                                                     commission.setCityId(user.getCityId());
                                                     commission.setAreaId(user.getAreaId());
                                                     commission.setCommissionName(user.getAllName());
                                                     commission.setCreateTime(sdf.format(new Date()));
                                                     commission.setIsDel(0);
                                                     int result = commissionDao.insertSelective(commission);
                                                     if (result > 0) {
                                                             user.setCommissionId(commission.getCommissionId());
                                                             user.setTag(1010L);
                                                     }
                                             }
                                     }
                             }
                     }
             }
             return null;
        }


        @RequestMapping(value = "/addUserByPhone",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil addUserByPhone(HttpServletRequest request,HttpServletResponse response,UserView user){
            try{
                DateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                User user1 = CacheData.getSessionUser(user.getUserId(),1);
                if(StringUtil.isEmpty(user.getUserName()))
                        return new ReturnResultUtil(500,MessageUtil.USERNAMECANNOTEMPTY);
                if(StringUtil.isEmpty(user.getPassword()))
                        return new ReturnResultUtil(500,MessageUtil.PASSWORDCANNOTEMPTY);
                if(StringUtil.isEmpty(user.getMobile()))
                        return new ReturnResultUtil(500,MessageUtil.MOBILECANNOTEMPTY);
                if(user.getHospitalId() != null){
                        user.setTag(1002L);
                        user.setType(1101L);
                }else if(user.getManufacturerId() != null){
                        user.setTag( 1004L);
                        user.setType(1102L);
                }else if(user.getMaintainerId() != null){
                        user.setTag( 1006L);
                        user.setType(1103L);
                }
/*                user.setUserId(UUIDGenerator.getUniqueLong());
                user.setPassword(MD5Util.md5(user.getPassword()));
                user.setUserId(null);
                user.setCreatePerson(user1.getUserId());*/
                user.setCreateTime(df.format(new Date()));
                user.setPyName(user.getRealName());
                return userService.addOrUpdateUser(user);
                }catch (Exception e){
                e.printStackTrace();
            }
                return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

        @RequestMapping(value = "/updatePyName",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil updatePyName(){
                List<User> users1 = userDao.queryUserNameList();
                for(User us : users1){
                        String name = us.getUserName();
                        if(!StringUtil.isEmpty(name)){
                                String pingYin = ChineseToEnglish.getPingYin(name);
                                User updateUser = new User();
                                updateUser.setUserId(us.getUserId());
                                updateUser.setPyName(pingYin);
                                userDao.updateUserPinYinName(updateUser);
                        }
                }
                return new ReturnResultUtil(200,"ok");
        }

        @RequestMapping(value = "/queryLoginUser",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public String queryloginUser(HttpServletRequest request,HttpServletResponse response){
                return JSON.toJSONString(CacheData.getSessionUser(null,1));
        }

        /**
         * 更新用户姓名
         * @param request
         * @param response
         * @param userView
         * @return
         */
        @RequestMapping(value = "/updateRealName",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil updateRealName(HttpServletRequest request,HttpServletResponse response,UserView userView){
                try{
                        if(userView.getUserId() == null){
                                return new ReturnResultUtil(500,MessageUtil.USERIDDOESTNOEXIST);
                        }
                        ReturnResultUtil rru = userService.updateRealName(userView);
                        return rru;
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(200,MessageUtil.SAVESUCCESS);
        }

        /**
         * 绑定微信号
         * @param request
         * @param response
         * @return
         */
        @RequestMapping(value = "/bindingWeiXin",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil bindingWeiXin(HttpServletRequest request,HttpServletResponse response,UserView userView){
                try {

                        if (userView.getUserId()==null) {
                                return new ReturnResultUtil(500, MessageUtil.USERIDDOESTNOEXIST);
                        }
                        if(userView.getOpenId() == null){
                                return new ReturnResultUtil(500,"OpenId不能为空");
                        }/*else{
                                userView.setOpenId(InitDataUitl.openIdMap.get(userView.getOpenId()));
                        }
*/
                        return userService.updateOpenId(userView);
                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.FAILED);
        }


        @RequestMapping(value = "/setUserMenu",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil setUserMenu(HttpServletRequest request,HttpServletResponse response,Long userId){
                try{
                     ReturnResultUtil rru = userService.querySysUrl(userId);
                     return rru;

                }catch (Exception e){
                        e.printStackTrace();
                }
                return new ReturnResultUtil(500,MessageUtil.QUERYEXCEPTION);
        }


        @RequestMapping(value = "/saveSetMenu",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil saveSetMenu(HttpServletRequest request,HttpServletResponse response,Long userId,String urlId){
           try{
                   List<Long> list = new ArrayList<>();
                   String [] strs = urlId.split(",");
                   for(String s : strs){
                           list.add(Long.parseLong(s));
                   }
                ReturnResultUtil rru = userService.saveSetMenu(userId,list);
                return rru;

           }catch (Exception e){
                e.printStackTrace();
           }
                return new ReturnResultUtil(500,MessageUtil.SAVESUCCESS);
        }





}
